package com.ruiysoft.security.manager;

import com.ruiysoft.security.provider.CustomDaoAuthenticationProvider;
import com.ruiysoft.security.provider.MicroprogramCodeProvider;
import com.ruiysoft.security.service.RedisUserDetailsService;
import com.ruiysoft.service.wechat.IWeChatService;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * Created by 化增光 on 2018/10/28.
 */
@Component
public class CustomAuthenticationManager {

    @Resource
    RedisUserDetailsService redisUserDetailsService;

    @Resource
    IWeChatService iWeChatService;

    /*@Autowired
    @Qualifier("DefaultBCryptPasswordEncoder")
    BCryptPasswordEncoder passwordEncoder;*/

    @Bean("authenticationManager")
    protected AuthenticationManager authenticationManager() throws Exception {
        ProviderManager authenticationManager = new ProviderManager(Arrays.asList(daoAuthenticationProvider(),microprogramCodeProvider()));
        //不擦除认证密码，擦除会导致TokenBasedRememberMeServices因为找不到Credentials再调用UserDetailsService而抛出UsernameNotFoundException
        authenticationManager.setEraseCredentialsAfterAuthentication(false);
        return authenticationManager;
    }

    protected DaoAuthenticationProvider daoAuthenticationProvider(){
        DaoAuthenticationProvider daoAuthenticationProvider = new CustomDaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());
        daoAuthenticationProvider.setUserDetailsService(redisUserDetailsService);
        return daoAuthenticationProvider;
    }
    protected MicroprogramCodeProvider microprogramCodeProvider(){
        MicroprogramCodeProvider microprogramCodeProvider = new MicroprogramCodeProvider();
        microprogramCodeProvider.setRedisUserDetailsService(redisUserDetailsService);
        microprogramCodeProvider.setiWeChatService(iWeChatService);
        return microprogramCodeProvider;
    }
//    protected MobileAuthenticationCodeProvider mobileAuthenticationCodeProvider(){
//        MobileAuthenticationCodeProvider mobileAuthenticationCodeProvider = new MobileAuthenticationCodeProvider();
//        mobileAuthenticationCodeProvider.setUserDetailsService(redisUserDetailsService);
//        return mobileAuthenticationCodeProvider;
//    }
}
